package com.jinzhi.jzweb.controller;


import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.common.controller.NewCertificatesApittController;
import com.jinzhi.jzapi.common.pojo.NewTrainingCertificatesUtilsVo;
import com.jinzhi.jzapi.utils.ITextPdfUtil;
import com.jinzhi.jzweb.domain.JzTrainCertificateDO;
import com.jinzhi.jzweb.pojo.NewTrainingCertificatesVO;
import com.jinzhi.jzweb.service.JzTrainCertificateService;
import com.jinzhi.jzweb.utils.*;
import com.jinzhi.oss.service.OssService;
import com.jinzhi.oss.service.impl.OssServiceImpl;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.domain.NewTrainingCertificatesDO;
import com.jinzhi.jzweb.service.NewTrainingCertificatesService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 培训证书
 * </pre>
 * <small> 2023-11-20 10:14:27 | Long</small>
 */
@Controller
@RequestMapping("/jzweb/newTrainingCertificates")
public class NewTrainingCertificatesController extends BaseController {
	@Autowired
	private NewTrainingCertificatesService newTrainingCertificatesService;


	@Autowired
	private JzTrainCertificateService jzTrainCertificateService;
	@Autowired
	private NewCertificatesApittController newCertificatesApittController;
	@Autowired
	private DictService dictService;

	@Autowired
	private OssServiceImpl ossService;

	private String QRurl = "/jinzhiFile/QRUpload/"; //二维码存放路径
//	private String QRurl = "D:/upload/erwei/"; //二维码存放路径

	private String selQRurl1 = "https://www.hnsyys.cn/common/erCodeFactory/getQRId"; //二维码查询回调方法路径
	private String selQRurl = "https://www.hnsyys.cn/common/erCodeFactory/getQRIds"; //二维码查询回调方法路径

	@GetMapping()
	String NewTrainingCertificates(){
	    return "jzweb/newTrainingCertificates/newTrainingCertificates";
	}

	@GetMapping("/selectcate")
	String selectcate(){
		return "common/erCodeFactory/selectcate";
	}

	@GetMapping("/selectcate3")
	String selectcate3(){
		return "common/erCodeFactory/selectcate3";
	}
	@ResponseBody
	@GetMapping("/list")
	public Result<Page<NewTrainingCertificatesDO>> list(NewTrainingCertificatesDO newTrainingCertificatesDTO){
		// 查询列表数据
		Page<NewTrainingCertificatesDO> page = newTrainingCertificatesService.selectPage(getPage(NewTrainingCertificatesDO.class),
					newTrainingCertificatesService.convertToEntityWrapper().orderBy("id", false));
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				NewTrainingCertificatesDO obj = (NewTrainingCertificatesDO) page.getRecords().get(i);
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	String add(){
	    return "jzweb/newTrainingCertificates/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id,Model model){
		NewTrainingCertificatesDO newTrainingCertificates = newTrainingCertificatesService.selectById(id);
		model.addAttribute("newTrainingCertificates", newTrainingCertificates);
	    return "jzweb/newTrainingCertificates/edit";
	}
	
	@Log("添加培训证书")
	@ResponseBody
	@PostMapping("/save")
	public Result<String> save( NewTrainingCertificatesDO newTrainingCertificates){
		newTrainingCertificatesService.insert(newTrainingCertificates);
        return Result.ok();
	}
	
	@Log("修改培训证书")
	@ResponseBody
	@RequestMapping("/update")
	public Result<String>  update( NewTrainingCertificatesDO newTrainingCertificates){
		boolean update = newTrainingCertificatesService.updateById(newTrainingCertificates);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除培训证书")
	@PostMapping( "/remove")
	@ResponseBody
	public Result<String>  remove( Long id){
		newTrainingCertificatesService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除培训证书")
	@PostMapping( "/batchRemove")
	@ResponseBody
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		newTrainingCertificatesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}







































	/**
	 * 证书类型查询
	 * @return
	 */
	@ResponseBody
	@GetMapping("/selCertificateType")
	public Result<List> selCertificateType(){
		List<String> list =new ArrayList<>();
		list.add("高级母婴护理师");
		list.add("保育师师资证书");
		list.add("整理收纳师");
		list.add("婴幼儿辅食师");
		list.add("早期教育指导师");
		list.add("家政保洁师");
		list.add("岗位能力培训合格证书");
		return Result.ok(list);
	}


	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<NewTrainingCertificatesVO> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "证书信息导入模板", "证书信息导入模板", NewTrainingCertificatesVO.class, "证书信息导入模板", response);
	}


	/**
	 * 培训证书信息导入
	 */
	@Log("培训证书信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	public Result<?> importExcel(@RequestParam("file") MultipartFile file, String ctype,String dateAdd) throws ParseException, IOException {
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}
		List<NewTrainingCertificatesVO> list = EasyPoiUtil.importExcel(file, 1, 1, NewTrainingCertificatesVO.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}
		if (StringUtils.isBlank(ctype)) {
			return Result.fail("证书类型未选择，请选择后导入！");
		}

		Map map = new HashMap();

		if (ctype.equals("高级母婴护理师")) {
			map.put("name", "高级母婴护理师");
			map.put("type", "gjmybjs_zs");
		}
		if (ctype.equals("保育师师资证书")) {
			map.put("name", "保育师师资证书");
			map.put("type", "baoyushishizi_zs");
		}
		if (ctype.equals("整理收纳师")) {
			map.put("name", "整理收纳师");
			map.put("type", "zlgns_zs");
		}
		if (ctype.equals("婴幼儿辅食师")) {
			map.put("name", "婴幼儿辅食师");
			map.put("type", "yyefss_zs");
		}
		if (ctype.equals("早期教育指导师")) {
			map.put("name", "早期教育指导师");
			map.put("type", "zqjy_zs");
		}
		if (ctype.equals("家政保洁师")) {
			map.put("name", "家政保洁师");
			map.put("type", "jzbjs_zs");
		}
		if (ctype.equals("岗位能力培训合格证书")) {
			map.put("name", "岗位能力培训合格证书");
			map.put("type", "gwnl_zs");
		}

		//查询证书模板
		String traSynthesis = dictService.selDicBy(map);
		if (StringUtils.isNotBlank(traSynthesis)) {
			traSynthesis = ValuesUtil.localUrl + traSynthesis;
		}

		//定义数据库修改集合以及证书生成集合
		List<NewTrainingCertificatesUtilsVo> newTrainingCertificatesUtilsVos =new ArrayList<>();
		List<NewTrainingCertificatesDO> newTrainingCertificatesDOS =new ArrayList<>();
		List<JzTrainCertificateDO> jzTrainCertificateDOS = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {



			if (ctype.equals("高级母婴护理师")||ctype.equals("保育师师资证书")||ctype.equals("整理收纳师")||ctype.equals("婴幼儿辅食师")
					||ctype.equals("早期教育指导师")||ctype.equals("家政保洁师")||ctype.equals("岗位能力培训合格证书")){
				String number="PXCHSTC";
				Boolean isEQ = true; //默认开启
				if (ctype.equals("保育师师资证书")){
					 number = "BYSSZTC"; //证书编号
				}else if (ctype.equals("整理收纳师")){
					number = "ZLGLZTC"; //证书编号
				}else if (ctype.equals("婴幼儿辅食师")){
					number = "YYEFSTC"; //证书编号
				}else if (ctype.equals("早期教育指导师")){
					number = "ZQJYSTC"; //证书编号
				}else if (ctype.equals("家政保洁师")){
					number = "JZBJSTC"; //证书编号
				}else if (ctype.equals("岗位能力培训合格证书")){
					number = "GWNLSTC"; //岗位能力培训
					isEQ = false; //关闭二维码生成
				}
				EntityWrapper<NewTrainingCertificatesDO> wrapper = new EntityWrapper<>();
				wrapper.eq("id_number", list.get(i).getIdNumber())
						.eq("type", ctype); // 添加对证书类型的过滤条件


				NewTrainingCertificatesDO isSfz = newTrainingCertificatesService.selectOne(wrapper);
				if (isSfz != null) {
					return Result.fail(list.get(i).getIdNumber() + "已生成" + ctype + "证书,请勿重复生成");
				}

				String dateNow =dateAdd;
				//具体的年、月、日可利用substring截取
				//dateNow.substring(开始下标，结束下标),下标原则：从0开始，包前不包后
				String cerYear = dateNow.substring(0, 4);
				String cerMath = dateNow.substring(5, 7);

//				int bh;
//				//查出最后一张证书的证书编号
//				String selNumber = newTrainingCertificatesService.seleCertificateNumbers1(number);
//				if(StringUtils.isEmpty(selNumber)){
//                   // 初始化序列号为当前年月+时间戳的一部分，确保唯一性
//					long timestampPart = System.currentTimeMillis() % 100000;
//					bh = (int) timestampPart; // 强制转换为 int 类型
//					// 确保初始序列号是五位数，不足前面补0
//					bh = Integer.parseInt(numberFill(bh));
//				}else {
//					bh = Integer.parseInt(selNumber.substring(13)) + 1;
//				}
				int bh;
				String selNumber = newTrainingCertificatesService.seleCertificateNumbers1(number);
				if (StringUtils.isEmpty(selNumber)) {
					// 初始化序列号为当前年月+时间戳的一部分，确保唯一性
					long timestampPart = System.currentTimeMillis() % 100000;
					bh = (int) timestampPart;
					bh = Integer.parseInt(numberFill(bh));
				} else {
					bh = Integer.parseInt(selNumber.substring(13)) + 1;
				}

				// 构建完整的证书编号，保证每个证书都有唯一的编号
				bh += i; // 确保在同一轮循环中递增
				number = number + cerYear + cerMath + numberFill(bh);
//				String selNumber = newTrainingCertificatesService.seleCertificateNumbers();
//				bh= Integer.parseInt(selNumber.substring(13));
				// 遍历列表中的每个元素以生成唯一的编号和二维码
//				bh = bh + 1 + i;
//				number = number + cerYear + cerMath + numberFill(bh);

//
				// 定义目标日期时间格式
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss");
				// 将目标日期时间字符串转换为LocalDateTime对象
				LocalDateTime targetDateTime = LocalDateTime.parse("2025:03:11 23:59:59", formatter);
				// 获取当前时间的LocalDateTime对象
				LocalDateTime currentDateTime = LocalDateTime.now();
				// 比较两个时间 3月11号之前用身份证查询二维码
				String QRFileurl = "";
				if(isEQ) {
					if (currentDateTime.isBefore(targetDateTime)) {
						//生成二维码，每个证书一个码，根据身份证号码确保唯一 原来的需求
						String value = selQRurl1 + "?id=" + list.get(i).getIdNumber();
						System.out.println("二维码内容++++++++++++++++++++++++++++++++++++++" + value);
						QrCodeUtil.createQrCode(value, QRurl, list.get(i).getIdNumber() + ".jpg");
						QRFileurl = QRurl + list.get(i).getIdNumber() + ".jpg"; //二维码地址
					} else {
						//------------新需求 根据产品编号确保证书唯一
						String value = selQRurl + "?id=" + number;
						System.out.println("二维码内容++++++++++++++++++++++++++++++++++++++" + value);
						QrCodeUtil.createQrCode(value, QRurl, number + ".jpg");
						QRFileurl = QRurl + number + ".jpg"; //二维码地址
					}
				}
//				String value = selQRurl+"?id="+list.get(i).getIdNumber();
//				System.out.println("二维码内容++++++++++++++++++++++++++++++++++++++"+value);
//				QrCodeUtil.createQrCode(value,QRurl,list.get(i).getIdNumber()+".jpg");
//				String QRFileurl =  QRurl+list.get(i).getIdNumber()+".jpg"; //二维码地址

				//------------新需求 根据产品编号确保证书唯一
//				String value = selQRurl+"?id="+number;
//				System.out.println("二维码内容++++++++++++++++++++++++++++++++++++++"+value);
//				QrCodeUtil.createQrCode(value,QRurl,number+".jpg");
//				String QRFileurl =  QRurl+number+".jpg"; //二维码地址

				NewTrainingCertificatesUtilsVo newTrainingCertificatesUtilsVo =new NewTrainingCertificatesUtilsVo();
				newTrainingCertificatesUtilsVo.setNumber(number); //证书编号
				newTrainingCertificatesUtilsVo.setStuImg(list.get(i).getStuImg()); //寸照地址
				newTrainingCertificatesUtilsVo.setType(ctype); //类型
				newTrainingCertificatesUtilsVo.setWebAddress("http://www.jzwy123.com");
				newTrainingCertificatesUtilsVo.setName(list.get(i).getName());//姓名
				newTrainingCertificatesUtilsVo.setQRImg(QRFileurl); //二维码地址
				newTrainingCertificatesUtilsVo.setBackgroundPath(traSynthesis); //证书模板地址
				newTrainingCertificatesUtilsVo.setYear(cerYear);//年
				newTrainingCertificatesUtilsVo.setMath(cerMath);//月

				NewTrainingCertificatesDO newTrainingCertificatesDO =new NewTrainingCertificatesDO();
				newTrainingCertificatesDO.setNumbers(number); //证书编号
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				newTrainingCertificatesDO.setGetTime(dateFormat.parse(dateAdd)); //获证时间
				newTrainingCertificatesDO.setState(0); //状态（0正常，1无效）
				newTrainingCertificatesDO.setType(ctype); //证书类型
				newTrainingCertificatesDO.setQrCode(QRFileurl);//二维码地址
				newTrainingCertificatesDO.setName(list.get(i).getName()); //姓名
				newTrainingCertificatesDO.setIdNumber(list.get(i).getIdNumber()); //身份证号
				newTrainingCertificatesDO.setYear(cerYear); //年份
				newTrainingCertificatesDO.setIdNumberType(list.get(i).getIdNumberType()); //证件类型
				newTrainingCertificatesDO.setCreaterDate(new Date()); //创建时间


				if (ctype.equals("岗位能力培训合格证书")) {
					JzTrainCertificateDO jzTrainCertificateDO = new JzTrainCertificateDO();
					jzTrainCertificateDO.setName(list.get(i).getName());//姓名
					jzTrainCertificateDO.setIdNumber(list.get(i).getIdNumber());//身份证号码
					jzTrainCertificateDO.setCertificateNumber(number);//证书编号
					jzTrainCertificateDO.setType("1");
					jzTrainCertificateDO.setCourseTitle("岗位能力培训合格证书");
					jzTrainCertificateDO.setPeriod("60");
					jzTrainCertificateDO.setGrade("100");
					jzTrainCertificateDO.setGetTime(dateFormat.parse(dateAdd));
					jzTrainCertificateDO.setUnit("无");
					jzTrainCertificateDO.setSex("未知");
					jzTrainCertificateDO.setImg("https://jinzhiweiye.oss-cn-hangzhou.aliyuncs.com/66765ad41e72cd3fa149982a5f9d2acd.png");
					jzTrainCertificateDOS.add(jzTrainCertificateDO);
				}

				if (ctype.equals("保育师师资证书")){
					newTrainingCertificatesDO.setIssuingUnit("长沙市金职伟业职业培训学校");
				}else if (ctype.equals("婴幼儿辅食师")||ctype.equals("早期教育指导师")){
					newTrainingCertificatesDO.setIssuingUnit("长沙市金职伟业职业培训学校,湖南省育婴师协会");
				}
				else {
					newTrainingCertificatesDO.setIssuingUnit("长沙市金职伟业职业培训学校,长沙市民政职业技术学院继续教育学院");

				}
				//转换一下图片路径，将反斜杠替换掉
				if (list.get(i).getStuImg()!=null) {
					String stuImgUrl = list.get(i).getStuImg().replace("\\", "/");

					File file1 = new File(stuImgUrl);
					InputStream inputStream = new FileInputStream(file1);
					MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
					String stuImgOssUrl = ossService.uploadFileOss(multipartFile);
//					newTrainingCertificatesDO.setStuImg(ValuesUtil.returnUrl+stuImgUrl); //寸照地址
					newTrainingCertificatesDO.setStuImg(stuImgOssUrl); //寸照地址
				}
				newTrainingCertificatesUtilsVos.add(newTrainingCertificatesUtilsVo);
				newTrainingCertificatesDOS.add(newTrainingCertificatesDO);
			}

		}
		if (ctype.equals("岗位能力培训合格证书")) {
			jzTrainCertificateService.insertBatch(jzTrainCertificateDOS);
		}
		newCertificatesApittController.doTask11(newTrainingCertificatesUtilsVos,newTrainingCertificatesDOS); //生成证书
		newTrainingCertificatesService.insertBatch(newTrainingCertificatesDOS); //插入数据
		return Result.ok("导入成功请二十分钟后刷新查看");
	}






	//填充方法
	private String numberFill(int number){
		String rstNumber;
		if (number>=1&&number<=9){ //一位数
			rstNumber = "0000" + number;
		}else if (number>=10&&number<=99){ //二位数
			rstNumber = "000" + number;
		}else if (number>=100&&number<=999){ //三位数
			rstNumber = "00" + number;
		}else if (number>=1000&&number<=9999){ //四位数
			rstNumber = "0" + number;
		}else {
			rstNumber = String.valueOf(number); //五位数
		}
		return rstNumber;
	}



	@GetMapping("/selNewTrainingCertificates")
	@ResponseBody
	public Result<NewTrainingCertificatesDO> selNewTrainingCertificates(String name,String idNumber){
		EntityWrapper wrapper =new EntityWrapper();
		wrapper.eq("name",name);
		wrapper.eq("id_number",idNumber);
		NewTrainingCertificatesDO newTrainingCertificatesDO = newTrainingCertificatesService.selectOne(wrapper);
		return Result.ok(newTrainingCertificatesDO);
	}



	private static String bs = ",";


	private static List<String> splitStrArrayList(String str) {
		List<String> stringList = new ArrayList<>();
		if (str != null) {
			String[] strs = str.split(bs);
			stringList.addAll(Arrays.asList(strs));
			return stringList;
		}
		return null;
	}





	/**
	 * 导出证书PDF文件
	 */
	@Log("导出证书PDF文件")
	@GetMapping("/exportPdf")
	@ResponseBody
	public void exportPdf(HttpServletRequest request, HttpServletResponse response,@RequestParam("ids") String ids) {
		List<String> list = splitStrArrayList(ids);
		List<String> imgUrlEnd = new ArrayList<>();
		List<NewTrainingCertificatesDO> newTrainingCertificatesDOS = newTrainingCertificatesService.selectBatchIds(list);
		for (NewTrainingCertificatesDO newTrainingCertificatesDO :newTrainingCertificatesDOS){
			if (newTrainingCertificatesDO.getImgUrl()!=null){
				imgUrlEnd.add(newTrainingCertificatesDO.getImgUrl());
			}
		}
		String paths = "证书信息导出";

				try {
					this.creatPdf(paths, imgUrlEnd);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (DocumentException e) {
					e.printStackTrace();
				}


				try {
					// path是指欲下载的文件的路径。
					File file = new File(ValuesUtil.localUrl + "/work/" + paths + ".pdf");
					String filepath = file.getPath();

					// 以流的形式下载文件。
					InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
					byte[] buffer = new byte[fis.available()];
					fis.read(buffer);
					fis.close();
					// 清空response
					response.reset();
					// 设置response的Header
					response.addHeader("Content-Disposition", "attachment;filename=" + new String((paths + ".pdf").getBytes(), "iso-8859-1"));
					response.addHeader("Content-Length", "" + file.length());
					OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
					response.setContentType("application/octet-stream");
					toClient.write(buffer);
					toClient.flush();
					toClient.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
	}


	public void creatPdf(String pdfName, List<String> imgUrls) throws IOException, DocumentException {
		Rectangle pageSize;
		// 第一步，实例化一个document对象
		pageSize = new Rectangle(1123F, 794F);

		Document document = new Document(pageSize, 50, 50, 0, 50);
		// 设置相关的参数
		ITextPdfUtil.setParameters(document, "开发者", "测试", "测试 开发者 调试", "lance", "lance");
		// 第二步，设置要到出的路径
		try {
			FileOutputStream out = new FileOutputStream(ValuesUtil.localUrl + "/work/" + pdfName + ".pdf");
			// 第三步，将pdf文件输出到磁盘
			PdfWriter writer = PdfWriter.getInstance(document, out);
			// 第四步，打开生成的pdf文件
			document.open();
			// 第五步，往pdf文档中添加证书图片
			for (int i = 0; i < imgUrls.size(); i++) {
				File file=new  File(imgUrls.get(i));
				if(true){
					Image image = Image.getInstance(imgUrls.get(i));
					image.setAlignment(Element.ALIGN_CENTER);//设置元素居中
					document.add(image);
				}
			}
			// 第八步，关闭document
			document.close();
			//文件输出至服务器
			String pdffilepath = ValuesUtil.localUrl + "\\work\\" + pdfName + ".pdf";
			String pdfpath = pdffilepath.replace("\\", "/");

			ITextPdfUtil.doAddWaterMark(pdfpath, pdfName, 38, "255, 200, 0", "4, 550", 10);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@GetMapping("/elderlyCare")
	String elderlyCare(){
		return "common/erCodeFactory/elderlyCare";
	}
	@GetMapping("/elderlyCareH5")
	String elderlyCareH5(){
		return "common/erCodeFactory/elderlyCareH5";
	}

}
